/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   Module Name          : com.yaodian100.ec.image.web.ImageAction
   Module Description   :

   Date Created      : 2009/11/19
   Original Author   : ellen.li
   Team              : yaodian100
   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   MODIFICATION HISTORY
   ------------------------------------------------------------------------------
   Date Modified       Modified by       Comments
   ------------------------------------------------------------------------------
   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
package com.yaodian100.ec.image.web;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang.xwork.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;
import com.yaodian100.core.common.dao.impl.CommonCriteria;
import com.yaodian100.core.common.utils.ServerValue;
import com.yaodian100.ec.image.entity.Image;
import com.yaodian100.ec.image.service.ImageService;
import com.yaodian100.ec.product.entity.Product;
import com.yaodian100.ec.product.service.ProductService;
import com.yaodian100.ec.proposeproduct.entity.ProposeProduct;
import com.yaodian100.ec.proposeproduct.service.ProposeProductService;

/**
 * @author ellen.li
 * 
 */
public class ImageAction extends ActionSupport implements Preparable {

	/**
	 * serial version
	 */
	private static final long serialVersionUID = 5207553092623180612L;
	private final Logger logger = LoggerFactory.getLogger(ImageAction.class);
	private ImageService imageService;
	private ProductService productService;
	private ProposeProductService proposeProductService;
	private Image image;
	private File[] imageM;
	private File[] imageDes;
	private File[] picImgs;
	private String[] picImgDetails;
	private String[] picImgDescs;
	private String[] picImgShowSeqs;
	private String[] imgIds;
	private String rData = "";
	private String savePath;
	private String productId;
	private String productName;
	private List<Image> images;
	private String[] imageMFileName;// 设置上传文件的文件名
	private String[] imageDesFileNames;
	private String subName;
	private StringBuffer imgMfilePath;
	private String imgType;
	private String pdFlag;
	private String picDesc;
	private String[] deletePic;
	private String imgId;
	private int imgSize;
	private Map<String, String> imageTypeMap;
	private String selImageType;

	public String list() throws Exception {
		return "list";
	}

	public String listP() throws Exception {
		return "listP";
	}

	public String deletePic() throws Exception {
		try {
			// logger.error("deletePic--------" + deletePic);
			// 刪除檔案
			if (null != deletePic) {
				imageService.deletePic(deletePic);
			}
			// 複蓋原圖檔
			String picImgNo;
			String picImgDesc;
			String picImgShowSeq;
			String msg;
			int i = 0;
			// logger.error("picImgs--------" + picImgs);
			if (null != picImgs) {
				File[] tempFile = new File[1];
				for (String picImgDetail : picImgDetails) {
					picImgNo = picImgDetail.split("θ")[0];
					picImgDesc = picImgDetail.split("θ")[1];
					picImgShowSeq = picImgDetail.split("θ")[2];
					tempFile[0] = picImgs[i];
					msg = imageService.editImgDetail(Long.parseLong(picImgNo), tempFile, picImgDesc, picImgShowSeq);
					if (StringUtils.isNotBlank(msg)) {
						addActionMessage(msg);
					}
					i++;
				}
			}
			// logger.error("imgIds----" + imgIds);
			i = 0;
			for (String picId : imgIds) {
				picImgDesc = picImgDescs[i];
				picImgShowSeq = picImgShowSeqs[i];
				msg = imageService.editImgDetail(Long.parseLong(picId), null, picImgDesc, picImgShowSeq);
				if (StringUtils.isNotBlank(msg)) {
					addActionMessage(msg);
				}
				i++;
			}
		} catch (Exception e) {
			addActionError(e.fillInStackTrace().toString());
		}
		deletePic = null;
		picImgs = null;
		imgIds = null;
		// logger.error("pdFlag----" + pdFlag);
		if (null != pdFlag && pdFlag.equals("PPT")) {
			return editPropose();
		} else {
			return edit();
		}
	}

	/**
	 * 選擇上傳圖檔
	 * 
	 * @return
	 * @throws Exception
	 */
	public String edit() throws Exception {
		try {
			if (StringUtils.isBlank(productId) || StringUtils.length(productId) != 8 || !NumberUtils.isNumber(productId)) {
				addActionError("传入参数错误");
				return list();
			} else {
				Product product = productService.get(productId);
				if (null == product) {
					addActionError("查无商品资料(或无该权限查看)");
					return list();
				} else {
					CommonCriteria crit = new CommonCriteria();
					productName = product.getProductName();
					crit.addNe("isDelete", "Y");
					crit.addEq("productId", productId);
					if (StringUtils.isBlank(selImageType)) {
						selImageType = "MAIN";
					}
					crit.addEq("type", selImageType);
					String[] sort = { "type", "showSeq asc", "id asc" };
					images = imageService.getList(0, -1, crit, sort);
					// 商品圖筆數(大小圖加起來不可大於20筆)
					crit = new CommonCriteria();
					crit.addEq("productId", productId);
					List<String> types = new ArrayList<String>();
					types.add("IMGB");
					types.add("IMGS");
					crit.addIn("type", types);
					crit.addNe("isDelete", "Y");
					imgSize = imageService.getListSize(crit).intValue();
				}
			}
		} catch (Exception e) {
			addActionError(e.fillInStackTrace().toString());
		}
		return "edit";
	}

	public String editImgDetail() throws Exception {
		imageService.editImgDetail(Long.parseLong(imgId), imageDes, picDesc);
		if (null != pdFlag && pdFlag.equals("PPT")) {
			return "successP";
		} else {
			return "success";
		}
	}

	/**
	 * 選擇提报商品上傳圖檔
	 * 
	 * @return
	 * @throws Exception
	 */
	public String editPropose() throws Exception {
		try {
			if (StringUtils.isBlank(productId) || StringUtils.length(productId) != 8 || !NumberUtils.isNumber(productId)) {
				addActionError("传入参数错误");
				return listP();
			} else {
				ProposeProduct product = proposeProductService.get(productId);
				if (null == product) {
					addActionError("查无商品资料(或无该权限查看)");
					return listP();
				} else {
					CommonCriteria crit = new CommonCriteria();
					productName = product.getName();
					crit.addNe("isDelete", "Y");
					crit.addEq("productId", productId);
					if (StringUtils.isBlank(selImageType)) {
						selImageType = "MAIN";
					}
					crit.addEq("type", selImageType);
					String[] sort = { "type", "showSeq asc", "id asc" };
					images = imageService.getList(0, -1, crit, sort);

					// 商品圖筆數(大小圖加起來不可大於20筆)
					crit = new CommonCriteria();
					crit.addEq("productId", productId);
					List<String> types = new ArrayList<String>();
					types.add("IMGB");
					types.add("IMGS");
					crit.addIn("type", types);
					crit.addNe("isDelete", "Y");
					imgSize = imageService.getListSize(crit).intValue();
				}
			}
		} catch (Exception e) {
			addActionError(e.fillInStackTrace().toString());
		}
		return "editPropose";
	}

	@Override
	public String execute() throws Exception {
		return SUCCESS;
	}

	public String[] getDeletePic() {
		return deletePic;
	}

	/**
	 * @return the image
	 */
	public Image getImage() {
		return image;
	}

	/**
	 * @return the imageDes
	 */
	public File[] getImageDes() {
		return imageDes;
	}

	/**
	 * @return the imageDesFileName
	 */
	public String[] getImageDesFileNames() {
		return imageDesFileNames;
	}

	/**
	 * @return the imageM
	 */
	public File[] getImageM() {
		return imageM;
	}

	/**
	 * @return the imageMFileName
	 */
	public String[] getImageMFileName() {
		return imageMFileName;
	}

	/**
	 * @return the images
	 */
	public List<Image> getImages() {
		return images;
	}

	/**
	 * @return the imageService
	 */
	public ImageService getImageService() {
		return imageService;
	}

	public Map<String, String> getImageTypeMap() {
		return imageTypeMap;
	}

	public String getImgId() {
		return imgId;
	}

	public String[] getImgIds() {
		return imgIds;
	}

	public int getImgSize() {
		return imgSize;
	}

	public String getImgType() {
		return imgType;
	}

	public String getPdFlag() {
		return pdFlag;
	}

	public String getPicDesc() {
		return picDesc;
	}

	public String[] getPicImgDescs() {
		return picImgDescs;
	}

	public String[] getPicImgDetails() {
		return picImgDetails;
	}

	public File[] getPicImgs() {
		return picImgs;
	}

	public String[] getPicImgShowSeqs() {
		return picImgShowSeqs;
	}

	/**
	 * @return the productId
	 */
	public String getProductId() {
		return productId;
	}

	/**
	 * @return the productName
	 */
	public String getProductName() {
		return productName;
	}

	public ProposeProductService getProposeProductService() {
		return proposeProductService;
	}

	/**
	 * @return the rData
	 */
	public String getrData() {
		return rData;
	}

	/**
	 * @return the savePath
	 */
	public String getSavePath() {
		return savePath;
	}

	public String getSelImageType() {
		return selImageType;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.opensymphony.xwork2.Preparable#prepare()
	 */
	@Override
	public void prepare() throws Exception {
		clearErrorsAndMessages();
		if (null == imageTypeMap) {
			imageTypeMap = new LinkedHashMap<String, String>();
			imageTypeMap.put("MAIN", "方形主檔图");
			imageTypeMap.put("RMAIN", "长形主檔图");
			imageTypeMap.put("DESC", "描述图");
			imageTypeMap.put("IMGB", "其他图");
		}
	}

	public void setDeletePic(String[] deletePic) {
		this.deletePic = deletePic;
	}

	/**
	 * @param image the image to set
	 */
	public void setImage(Image image) {
		this.image = image;
	}

	/**
	 * @param imageDes the imageDes to set
	 */
	public void setImageDes(File[] imageDes) {
		this.imageDes = imageDes;
	}

	/**
	 * @param imageDesFileName the imageDesFileName to set
	 */
	public void setImageDesFileNames(String[] imageDesFileNames) {
		this.imageDesFileNames = imageDesFileNames;
	}

	/**
	 * @param imageM the imageM to set
	 */
	public void setImageM(File[] imageM) {
		this.imageM = imageM;
	}

	/**
	 * @param imageMFileName the imageMFileName to set
	 */
	public void setImageMFileName(String[] imageMFileName) {
		this.imageMFileName = imageMFileName;
	}

	/**
	 * @param images the images to set
	 */
	public void setImages(List<Image> images) {
		this.images = images;
	}

	/**
	 * @param imageService the imageService to set
	 */
	public void setImageService(ImageService imageService) {
		this.imageService = imageService;
	}

	public void setImageTypeMap(Map<String, String> imageTypeMap) {
		this.imageTypeMap = imageTypeMap;
	}

	public void setImgId(String imgId) {
		this.imgId = imgId;
	}

	public void setImgIds(String[] imgIds) {
		this.imgIds = imgIds;
	}

	public void setImgSize(int imgSize) {
		this.imgSize = imgSize;
	}

	public void setImgType(String imgType) {
		this.imgType = imgType;
	}

	public void setPdFlag(String pdFlag) {
		this.pdFlag = pdFlag;
	}

	public void setPicDesc(String picDesc) {
		this.picDesc = picDesc;
	}

	public void setPicImgDescs(String[] picImgDescs) {
		this.picImgDescs = picImgDescs;
	}

	public void setPicImgDetails(String[] picImgDetails) {
		this.picImgDetails = picImgDetails;
	}

	public void setPicImgs(File[] picImgs) {
		this.picImgs = picImgs;
	}

	public void setPicImgShowSeqs(String[] picImgShowSeqs) {
		this.picImgShowSeqs = picImgShowSeqs;
	}

	/**
	 * @param productId the productId to set
	 */
	public void setProductId(String productId) {
		this.productId = productId;
	}

	/**
	 * @param productName the productName to set
	 */
	public void setProductName(String productName) {
		this.productName = productName;
	}

	/**
	 * @param productService the productService to set
	 */
	public void setProductService(ProductService productService) {
		this.productService = productService;
	}

	public void setProposeProductService(ProposeProductService proposeProductService) {
		this.proposeProductService = proposeProductService;
	}

	/**
	 * @param rData the rData to set
	 */
	public void setrData(String rData) {
		this.rData = rData;
	}

	/**
	 * @param savePath the savePath to set
	 */
	public void setSavePath(String savePath) {
		this.savePath = savePath;
	}

	public void setSelImageType(String selImageType) {
		this.selImageType = selImageType;
	}

	public String toEditImgDetail() {
		if (!StringUtils.isBlank(imgId)) {
			image = imageService.get(Long.parseLong(imgId));
		}
		setImage(image);
		return "editImgDetail";
	}

	/**
	 * 上傳說明圖片
	 * 
	 * @return
	 * @throws Exception
	 */
	public String uploadImgDesc() throws Exception {
		try {
			if (null != imageDes) {
				if (imgType.equals("DESC")) {
					imageService.uploadImage(productId, "DESC", imageDes, imageDesFileNames, picDesc);
					selImageType = imgType;
				}
				if (imgType.equals("PRDT")) {
					imageService.uploadImage(productId, "PRDT", imageDes, null, picDesc);
					selImageType = "IMGB";
				}
				// 开始删图
				File fileDel = new File(ServerValue.getMidApachePath() + File.separator + "PImg" + File.separator);
				File[] files = fileDel.listFiles(new FilenameFilter() {
					public boolean accept(File dir, String name) {
						return name.length() != 4
								&& ("logo_ok_b.png,blank_75.gif,blank_500.gif,blank_50.gif,blank_250.gif,blank_135.gif,blank_100.gif,tmpZip,blank_r93.gif,blank_r130.gif,blank_r180.gif,blank_r330.gif,blank_r225.gif,blank_r530.gif,40x40.gif,blank_225.gif,blank_r99.gif"
										.indexOf(name) == -1);
					}
				});
				if (null != files) {
					for (int i = 0; i < files.length; i++) {
						FileUtils.forceDelete(files[i]);
					}
				}
			}
		} catch (Exception e) {
			addActionError(e.fillInStackTrace().toString());
		}
		imageDes = null;
		if (null != pdFlag && pdFlag.equals("PPT")) {
			return editPropose();
		} else {
			return edit();
		}
	}

	/**
	 * 上傳主檔圖片
	 * 
	 * @return
	 * @throws Exception
	 */
	public String uploadImgM() throws Exception {
		if (null != getImageM()) {
			try {
				// 先刪除已存在的主圖檔
				List<Image> imagelist;
				CommonCriteria crit = new CommonCriteria();
				crit.addEq("productId", productId);
				crit.addEq("type", imgType);
				imagelist = imageService.getList(0, -1, crit, null);
				if (imagelist.size() > 0) {
					for (Image img : imagelist) {
						imageService.delete(img);
					}
				}
				// 再上傳主檔圖片
				imageService.uploadImage(productId, imgType, getImageM(), null, picDesc);
				// 开始删图
				File fileDel = new File(ServerValue.getMidApachePath() + File.separator + "PImg" + File.separator);
				File[] files = fileDel.listFiles(new FilenameFilter() {
					public boolean accept(File dir, String name) {
						return name.length() != 4
								&& ("logo_ok_b.png,blank_75.gif,blank_500.gif,blank_50.gif,blank_250.gif,blank_135.gif,blank_100.gif,tmpZip,blank_r93.gif,blank_r130.gif,blank_r180.gif,blank_r330.gif,blank_r225.gif,blank_r530.gif,40x40.gif,blank_225.gif,blank_r99.gif"
										.indexOf(name) == -1);
					}
				});
				if (null != files) {
					for (int i = 0; i < files.length; i++) {
						FileUtils.forceDelete(files[i]);
					}
				}
			} catch (Exception e) {
				addActionError(e.fillInStackTrace().toString());
			}
		}
		imageM = null;
		selImageType = imgType;
		if (null != pdFlag && pdFlag.equals("PPT")) {
			return editPropose();
		} else {
			return edit();
		}
	}
}